package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏西西
 * Date: 2023-09-04
 * Time: 8:56
 */
//自己写的阻塞队列
    //暂时不考虑泛型。直接使用int来表示元素类型
class MyBlockingQueue{
    private int[] items = new int[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    //入队列
    public void put(int value) throws InterruptedException {
        synchronized (this) {
            while (size == items.length){
                //队列满了，不能继续插入
                //return;
                //进行阻塞等待
                this.wait();
            }
            items[tail] =value;
            tail++;
            //记得针对tail的处理
            //1)
            // tail = tail % items.length;
            //2)
            if(tail >= items.length){
                tail = 0;
            }
            size++;
            //唤醒的是take中的wait
            this.notify();
        }
    }

    //出队列
    public Integer take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            if(size ==0){
                //队列空，不能出队列
                //return null;
                //队列空，也应该阻塞
                this.wait();
            }
            result = items[head];
            head++;
            if(head >= items.length){
                head = 0;
            }
            size --;
            //唤醒put中的wait
            this.notify();
        }
        return  result;
    }

}
public class ThreadDemo23 {
    public static void main(String[] args) throws InterruptedException {
//        MyBlockingQueue queue = new MyBlockingQueue();
//        queue.put(1);
//        queue.put(2);
//        queue.put(3);
//        queue.put(4);
//        int result = 0;
//        result = queue.take();
//        System.out.println("result = " +result );
//        result = queue.take();
//        System.out.println("result = " +result );
//        result = queue.take();
//        System.out.println("result = " +result );
//        result = queue.take();
//        System.out.println("result = " +result );

        //再写一次
        MyBlockingQueue queue = new MyBlockingQueue();

        Thread customer = new Thread(() -> {
            //消费操作
            while(true){
                try {
                    int result = queue.take();
                    System.out.println("消费："+result);
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        customer.start();
        //生产者线程
        Thread producer = new Thread(() ->{
            int count = 0;
            while (true){
                try {
                    System.out.println("生产：" +count);
                    queue.put(count);
                    count++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        producer.start();
    }
}
